import { defineStore } from "pinia";
import { ref } from "vue";
import {ElMessage} from 'element-plus'


export const useUserStore = defineStore('user',()=>{
    //当前登录用户名称
    const currentUser = ref("");
    //是否登录
    const isLogin = ref(localStorage.getItem('xdclass_user_is_login') === true ? true : false);
    //注册的用户信息
    const user = ref({
        account:"",
        password:"",
    });

//登录
const login = (account,password)=>{
    const foundUser = user.value.account === account && user.value.password === password;
    if(foundUser){
        localStorage.setItem("xdclass_user_is_login",true);
        localStorare.setItem("xdclass_user_current_user",account);
        ElMessage({
            message:"登录成功",
            type:"success",
        });
        isLogin.value = true;
        currentUser.value = account;
    }else {
        ElMessage({
            message:"账号或密码错误",
            type:"error",
        });
    }

};

//退出
const logout = ()=>{
   user.value={ 
       account:"",
       password:"",
    };
    currentUser.value ="";
    isLogin.value = false;
    localStorage.removeItem("xdclass_user_current_user");
    localStorage.setItem("xdclass_user_is_login",false);
    localStorage.removeItem("cdclass_vue_user");
    ElMessage({
        message:"退出成功",
        type:"succes",
    });


};

//注册更新用户
const register =(account,password)=>{
   user.value = {account,password};
   //数据缓存
   localStorage.setItem("cdclass_vue_user",JSON.stringify(user));
   localStorage.setItem("xdclass_user_is_login",true);
   isLogin.value = true;
   currentUser.value = account;
};

return(currentUser, isLogin, user, login, register,logout)

},
{
    persist:{
        enbled:true, //Store中数据持久化生效
    }
}
);
